<?php

namespace app\common\library;


class Wechat
{

    public function getOpenId($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config('site.app_id') . "&secret=" . config('site.appsecret') . "&code=" . $code . "&grant_type=authorization_code";
        $res = $this->http_curl($url);
        return ['openid' => $res['openid'], 'access_token' => $res['access_token']];
    }

    public function getUserInfo($openid, $access_token)
    {
        //获取用户授权信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN";
        $res = $this->http_curl($url);
        return $res;
    }


    /**
     * 微信jssdk接口
     * @return array
     */
    public function weixinsdk()
    {
        $appid = config('site.app_id');
        $secret = config('site.appsecret');
        $cacheKey = "wx-mp-js-ticket-{$appid}";
        $ticket = cache($cacheKey);
        if ($ticket == false) {
            $token = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
            $tokenData = $this->http_curl($token);
            $jsapi_ticket = $this->http_curl('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $tokenData['access_token'] . '&type=jsapi');
            if ($jsapi_ticket) {
                cache($cacheKey, $jsapi_ticket['ticket'], $jsapi_ticket['expires_in'] - 600);
            }
        }
        $jsapi_ticket = $ticket;
        $timestamp = time();
        $url = $_SERVER['HTTP_REFERER'];
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }


        $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signPackage = array(
            'appId' => $appid,
            'timestamp' => $timestamp,
            'nonceStr' => $nonceStr,
            'signature' => sha1($string),
        );
        return $signPackage;
    }

    public function http_curl($url, $type = 'get', $res = 'json', $arr = '')
    {
        //1.初始化curl
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3.采集
        $output = curl_exec($ch);
        //4.关闭
        curl_close($ch);
        if ($res == 'json') {
            return json_decode($output, true);
        }
    }
}